import React, { useState, useRef, useEffect } from 'react';
import { Button, List, message, Upload, Modal, Card, Row, Col } from 'antd';
import { UploadOutlined, DeleteOutlined, PlayCircleOutlined } from '@ant-design/icons';
import type { UploadFile } from 'antd/es/upload/interface';
import { S3Client, PutObjectCommand, DeleteObjectCommand, ListObjectsCommand } from '@aws-sdk/client-s3';
import { s3Config } from '../config/s3Config';

const s3Client = new S3Client(s3Config);

interface VideoManagerProps {
  onVideoChange?: (videos: UploadFile[]) => void;
}

const VideoManager: React.FC<VideoManagerProps> = ({ onVideoChange }) => {
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewVideo, setPreviewVideo] = useState<string>('');
  const videoRef = useRef<HTMLVideoElement>(null);
  const thumbnailRefs = useRef<{ [key: string]: HTMLVideoElement }>({});

  useEffect(() => {
    fetchVideos();
  }, []);

  const generateThumbnail = (videoUrl: string, videoKey: string) => {
    const video = document.createElement('video');
    video.src = videoUrl;
    video.crossOrigin = 'anonymous';
    video.currentTime = 1; // 设置到视频的第1秒处获取缩略图
    
    video.onloadeddata = () => {
      const canvas = document.createElement('canvas');
      canvas.width = 320;  // 设置缩略图宽度
      canvas.height = 180; // 设置缩略图高度
      const ctx = canvas.getContext('2d');
      if (ctx) {
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        const thumbnailUrl = canvas.toDataURL('image/jpeg');
        // 更新文件列表中的缩略图
        setFileList(prev => prev.map(file => 
          file.uid === videoKey ? { ...file, thumbUrl: thumbnailUrl } : file
        ));
      }
    };
  };

  const fetchVideos = async () => {
    try {
      const response = await s3Client.send(new ListObjectsCommand({
        Bucket: s3Config.bucket
      }));
      
      if (response.Contents) {
        const videoFiles = response.Contents
          .filter(item => {
            const key = item.Key || '';
            return key.match(/\.(mp4|webm|ogg|mov)$/i);
          })
          .map(item => {
            const key = item.Key || '';
            const url = `${s3Config.endpoint}/${s3Config.bucket}/${key}`;
            const file = {
              uid: key,
              name: key,
              status: 'done',
              url: url,
              size: item.Size,
            } as UploadFile;
            
            // 为每个视频生成缩略图
            generateThumbnail(url, key);
            
            return file;
          });
        setFileList(videoFiles);
      }
    } catch (error) {
      message.error('获取视频列表失败');
    }
  };

  const handleUpload = async (file: File) => {
    try {
      const buffer = await file.arrayBuffer();
      const key = file.name;
      
      const command = new PutObjectCommand({
        Bucket: s3Config.bucket,
        Key: key,
        Body: buffer,
        ContentType: file.type
      });

      await s3Client.send(command);
      message.success('上传成功');
      fetchVideos();
      return false;
    } catch (error) {
      console.error('上传失败:', error);
      message.error('上传失败');
      return false;
    }
  };

  const handlePreview = async (file: UploadFile) => {
    setPreviewVideo(file.url || '');
    setPreviewOpen(true);
  };

  const handleRemove = async (file: UploadFile) => {
    try {
      const command = new DeleteObjectCommand({
        Bucket: s3Config.bucket,
        Key: file.name
      });

      await s3Client.send(command);
      message.success('删除成功');
      fetchVideos();
    } catch (error) {
      message.error('删除失败');
    }
    return true;
  };

  const uploadProps = {
    beforeUpload: (file: File) => {
      const isVideo = file.type.startsWith('video/');
      if (!isVideo) {
        message.error('只能上传视频文件！');
        return false;
      }
      const isLt500M = file.size / 1024 / 1024 < 500;
      if (!isLt500M) {
        message.error('视频大小不能超过 500MB！');
        return false;
      }
      return handleUpload(file);
    },
    fileList,
    showUploadList: false,
    multiple: true,
  };

  return (
    <div className="video-manager">
      <div className="upload-area">
        <Upload {...uploadProps}>
          <Button icon={<UploadOutlined />} size="large">上传视频</Button>
          <div style={{ marginTop: '8px', color: '#666' }}>
            支持 MP4、WebM、OGG、MOV 格式，单个文件最大 500MB
          </div>
        </Upload>
      </div>

      <Row gutter={[16, 16]} className="video-grid">
        {fileList.map(item => (
          <Col key={item.uid} xs={24} sm={12} md={8} lg={6}>
            <Card
              hoverable
              className="video-card"
              cover={
                <div 
                  className="video-card-cover"
                  onClick={() => handlePreview(item)}
                >
                  {item.thumbUrl ? (
                    <img 
                      src={item.thumbUrl} 
                      alt={item.name}
                      className="video-preview"
                    />
                  ) : (
                    <PlayCircleOutlined style={{ fontSize: '48px', opacity: 0.5 }} />
                  )}
                  <div className="video-info">
                    {((item.size || 0) / 1024 / 1024).toFixed(2)} MB
                  </div>
                </div>
              }
              actions={[
                <Button 
                  type="text" 
                  icon={<PlayCircleOutlined />} 
                  onClick={() => handlePreview(item)}
                >
                  播放
                </Button>,
                <Button 
                  type="text" 
                  icon={<DeleteOutlined />} 
                  danger 
                  onClick={() => handleRemove(item)}
                >
                  删除
                </Button>
              ]}
            >
              <Card.Meta
                title={
                  <div className="video-title">
                    {item.name}
                  </div>
                }
              />
            </Card>
          </Col>
        ))}
      </Row>

      <Modal
        open={previewOpen}
        title="视频预览"
        width="80%"
        style={{ 
          maxWidth: '1000px',
          top: 20
        }}
        footer={null}
        onCancel={() => {
          setPreviewOpen(false);
          if (videoRef.current) {
            videoRef.current.pause();
          }
        }}
      >
        <div className="video-player-container">
          <video
            ref={videoRef}
            controls
            className="video-player"
            src={previewVideo}
          />
        </div>
      </Modal>
    </div>
  );
};

export default VideoManager; 